const News = require("../../models/news.model");
class NewsService {
  async createNews(news) {
    const res = await News.create(news);
    return res.dataValues;
  }

  async findNews(pageNum, pageSize) {
    // //获取总数
    // const count = await Goods.count();
    // //获取分页的数据
    // const offset = (pageNum - 1) * pageSize;
    // const rows = await Goods.findAll({ offset: offset, limit: pageSize * 1 });

    const offset = (pageNum - 1) * pageSize;
    const { count, rows } = await News.findAndCountAll({
      offset: offset,
      limit: pageSize * 1,
      attributes: [
        "id",
        "title",
        "cover",
        "content",
        "category",
        "isPublish",
        "editTime",
      ],
    });

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    };
  }

  async newsPublish({ id, isPublish, editTime }) {
    return News.update({ isPublish, editTime }, { where: { id } });
  }

  async delNews(id) {
    const res = await News.destroy({ where: { id } });

    return res > 0 ? true : false;
  }

  async findANew({ id }) {
    const res = await News.findOne({ where: { id } });

    return res !== null ? res : null;
  }

  async updateById({
    id,
    title,
    content,
    category,
    isPublish,
    cover,
    editTime,
  }) {
    try {
      // console.log(id, user_name, gender, introduction);

      // 验证 id 是否存在
      if (!id) {
        throw new Error("更新新闻信息时必须提供 id");
      }

      // 定义更新条件
      const whereOptions = { id };
      // 存储需要更新的用户信息
      const updatedNews = {};

      // 添加非空字段到 updatedUser 对象
      if (title) Object.assign(updatedNews, { title });
      if (content) Object.assign(updatedNews, { content });
      if (isPublish) Object.assign(updatedNews, { isPublish });
      if (category) Object.assign(updatedNews, { category });
      if (cover) Object.assign(updatedNews, { cover });
      if (editTime) Object.assign(updatedNews, { editTime });

      // 执行数据库更新操作
      const result = await News.update(updatedNews, { where: whereOptions });

      // 根据更新结果返回布尔值
      return result[0] > 0;
    } catch (error) {
      // 处理错误
      console.error("更新新闻信息时出现错误:", error);
      return false;
    }
  }
}

module.exports = new NewsService();
